package cn.tedu._05mvcboot04.controller;

import cn.tedu._05mvcboot04.base.response.JsonResult;
import cn.tedu._05mvcboot04.base.response.StatusCode;
import cn.tedu._05mvcboot04.mapper.ArticleMapper;
import cn.tedu._05mvcboot04.mapper.UserMapper;
import cn.tedu._05mvcboot04.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot04.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot04.pojo.entity.Article;
import cn.tedu._05mvcboot04.pojo.vo.ArticleVO;
import cn.tedu._05mvcboot04.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Slf4j
@Api(tags = "用户文章")
@RestController
@RequestMapping("/v1/users/")
@Validated
public class UserArticleController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @PostMapping("login")
    @ApiOperation("登录功能")
    public JsonResult login(@Validated @RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.debug("userLoginDTO="+userLoginDTO);
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        UserVO userVO = new UserVO();
        userVO = userMapper.selectLogin(username,password);
        log.debug("userVO="+userVO);
        if (userVO==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);
        return new JsonResult(StatusCode.OPERATION_SUCCESS);
    }
    @ApiOperation("文章发布")
    @PostMapping("article")
    public JsonResult article(@RequestBody @Validated UserArticleDTO userArticleDTO,@ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        log.debug("userVO="+userVO);
        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(userVO.getId());
        articleMapper.insert(article);
        return new JsonResult(StatusCode.OPERATION_SUCCESS);
    }
    @ApiOperation("文章查询")
    @GetMapping("selectByArticleId")
    public JsonResult selectByArticleId(@Range(min = 1,max = 100)@RequestParam Long id){
        ArticleVO articleVO=articleMapper.selectByArticleId(id);
        log.debug("articleVO="+articleVO);
        return new JsonResult(StatusCode.OPERATION_SUCCESS,articleVO);
    }
}
